package com.waijiaojun.tpo.utils;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.util.Assert;

/**
 * Created by Peter on 2018/1/20.
 */
public class XmlUtil {
    private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();

    /**
     * Java Object->Xml with default encoding UTF-8.
     */
    public static String toXml(Object root) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(Reflections.getUserClass(root), "utf-8").marshal(root, writer);
            return writer.toString().replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Java Object->Xml with encoding.
     */
    public static String toXml(Object root, Class clazz, String encoding) {
        try {
            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(root, writer);
            return writer.toString().replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
     */
    public static String toXml(Collection<?> root, String rootName, Class clazz) {
        return toXml(root, rootName, clazz, null);
    }

    /**
     * Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
     */
    public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
        try {
            CollectionWrapper wrapper = new CollectionWrapper();
            wrapper.collection = root;

            JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
                    CollectionWrapper.class, wrapper);

            StringWriter writer = new StringWriter();
            createMarshaller(clazz, encoding).marshal(wrapperElement, writer);

            return writer.toString().replaceAll("&lt;", "<").replaceAll("&gt;", ">");
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Xml->Java Object.
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromXml(String xml, Class<T> clazz) {
        try {
            StringReader reader = new StringReader(xml);
            return (T) createUnmarshaller(clazz).unmarshal(reader);
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建Marshaller并设定encoding(可为null).
     * 线程不安全，需要每次创建或pooling。
     */
    public static Marshaller createMarshaller(Class clazz, String encoding) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);

            Marshaller marshaller = jaxbContext.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            if (StringUtils.isNotBlank(encoding)) {
                marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            }

            return marshaller;
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建UnMarshaller.
     * 线程不安全，需要每次创建或pooling。
     */
    public static Unmarshaller createUnmarshaller(Class clazz) {
        try {
            JAXBContext jaxbContext = getJaxbContext(clazz);
            return jaxbContext.createUnmarshaller();
        } catch (JAXBException e) {
            throw new RuntimeException(e);
        }
    }

    protected static JAXBContext getJaxbContext(Class clazz) {
        Assert.notNull(clazz, "'clazz' must not be null");
        JAXBContext jaxbContext = jaxbContexts.get(clazz);
        if (jaxbContext == null) {
            try {
                jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
                jaxbContexts.putIfAbsent(clazz, jaxbContext);
            } catch (JAXBException ex) {
                throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
                        + "]: " + ex.getMessage(), ex);
            }
        }
        return jaxbContext;
    }

    /**
     * 封装Root Element 是 Collection的情况.
     */
    public static class CollectionWrapper {

        @XmlAnyElement
        protected Collection<?> collection;
    }

    /**
     * xml to map
     *
     * @param xml
     * @return
     * @throws DocumentException
     */
    public static Map<String, String> toMap(String xml) throws DocumentException {
        Document document = DocumentHelper.parseText(xml);
        Element root = document.getRootElement();

        Map<String, String> map = new HashMap<String, String>();

        // iterate through child elements of root
        for (@SuppressWarnings("unchecked")
             Iterator<Element> i = root.elementIterator(); i.hasNext(); ) {
            Element e = i.next();
            map.put(e.getName(), e.getStringValue().replace("<![CDATA[", "").replace("]]>", ""));
        }

        return map;
    }

    public static void main(String[] args) throws DocumentException {
        String xml = "<xml>"
                + "<return_code><![CDATA[SUCCESS]]></return_code>"
                + " <return_msg><![CDATA[OK]]></return_msg>"
                + "<appid><![CDATA[wx2421b1c4370ec43b]]></appid>"
                + "<mch_id><![CDATA[10000100]]></mch_id>"
                + "<nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>"
                + "<sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>"
                + "<result_code><![CDATA[SUCCESS]]></result_code>"
                + "<prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>"
                + "<trade_type><![CDATA[JSAPI]]></trade_type>"
                + "</xml>";
        System.out.println(toMap(xml));

    }

}
